<template>
  <view class="seat-page">
    <!-- 顶部工具栏 -->
    <view class="toolbar">
      <!-- 座位状态图例 -->
      <view class="seat-legend">
        <view class="legend-item">
          <view class="legend-dot available"></view>
          <text class="legend-text">空闲</text>
        </view>
        <view class="legend-item">
          <view class="legend-dot occupied"></view>
          <text class="legend-text">占用</text>
        </view>
        <view class="legend-item">
          <view class="legend-dot selected"></view>
          <text class="legend-text">已选</text>
        </view>
        <view class="legend-item">
          <view class="legend-dot maintenance"></view>
          <text class="legend-text">维修</text>
        </view>
        <view class="legend-item">
          <view class="legend-dot vip"></view>
          <text class="legend-text">VIP</text>
        </view>
      </view>
      
      <!-- 区域筛选 -->
      <view class="area-filter">
        <scroll-view class="filter-scroll" scroll-x>
          <view 
            class="filter-item" 
            :class="{ active: selectedArea === 'all' }"
            @click="filterByArea('all')"
          >
            全部区域
          </view>
          <view 
            v-for="area in seatStore.seatLayout.areas" 
            :key="area.name"
            class="filter-item" 
            :class="{ active: selectedArea === area.name }"
            @click="filterByArea(area.name)"
          >
            {{ area.name }}
          </view>
        </scroll-view>
      </view>
      
      <!-- 座位统计 -->
      <view class="seat-summary">
        <text class="summary-text">
          空闲 {{ seatStore.seatStats.available }} / 总计 {{ seatStore.seatStats.total }}
        </text>
        <text class="update-time">{{ formatTime(seatStore.lastUpdateTime, 'HH:mm') }} 更新</text>
      </view>
    </view>
    
    <!-- 座位布局图 -->
    <scroll-view 
      class="seat-container" 
      scroll-y 
      refresher-enabled 
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="seat-layout">
        <!-- 区域标题和座位 -->
        <view v-for="area in visibleAreas" :key="area.name" class="area-section">
          <view class="area-header">
            <text class="area-title" :style="{ color: area.color }">{{ area.name }}</text>
            <text class="area-count">
              空闲: {{ getAreaAvailableCount(area) }} / {{ getAreaTotalCount(area) }}
            </text>
          </view>
          
          <!-- 座位网格 -->
          <view class="seat-grid">
            <view 
              v-for="seat in getAreaSeats(area)" 
              :key="seat.id"
              class="seat-item"
              :class="getSeatClass(seat)"
              @click="selectSeat(seat)"
              @longpress="showSeatDetail(seat)"
            >
              <text class="seat-number">{{ seat.number }}</text>
              <text v-if="seat.status === 'occupied'" class="seat-time">
                {{ getRemainingTime(seat) }}
              </text>
              <view v-if="seat.status === 'maintenance'" class="maintenance-icon">
                <text class="icon">🔧</text>
              </view>
              <view v-if="seat.area === 'VIP区'" class="vip-badge">
                <text class="vip-text">VIP</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="visibleSeats.length === 0" class="empty-state">
          <view class="empty-icon">🪑</view>
          <text class="empty-title">该区域暂无座位</text>
          <text class="empty-desc">请选择其他区域查看</text>
        </view>
      </view>
    </scroll-view>
    

    
    <!-- 底部操作栏 -->
    <view v-if="seatStore.selectedSeats.length > 0" class="bottom-actions safe-area-inset-bottom">
      <view class="selected-info">
        <view class="selected-seat">
          <text class="seat-name">{{ selectedSeatInfo.number }}</text>
          <text class="seat-area">{{ selectedSeatInfo.area }}</text>
        </view>
        <view class="seat-price">
          <text class="price-text">¥{{ selectedSeatInfo.price }}/小时</text>
          <text class="price-desc">{{ selectedSeatInfo.area === 'VIP区' ? 'VIP专享' : '标准价格' }}</text>
        </view>
      </view>
      
      <button class="booking-btn" @click="goToBooking">
        <text class="btn-text">立即预约</text>
        <text class="btn-icon">→</text>
      </button>
    </view>
    
    <!-- 座位详情弹窗 -->
    <uni-popup
      ref="seatDetailPopup"
      type="bottom"
      background-color="transparent"
      v-if="showDetailPopup"
      @maskClick="closeSeatDetail"
    >
      <view class="seat-detail-popup">
        <!-- 拖拽指示器 -->
        <view class="drag-indicator">
          <view class="drag-bar"></view>
        </view>

        <view class="popup-header">
          <text class="popup-title">座位详情</text>
          <view class="popup-close" @click="closeSeatDetail" @tap="closeSeatDetail">
            <text class="close-icon">×</text>
          </view>
        </view>

        <scroll-view v-if="detailSeat && showDetailPopup" class="seat-detail-content" scroll-y>
          <!-- 座位基本信息 -->
          <view class="detail-section">
            <text class="detail-title">座位信息</text>
            <view class="seat-info-card">
              <view class="seat-main-info">
                <text class="seat-big-number">{{ detailSeat.number }}</text>
                <view class="seat-status-badge" :class="getStatusClass(detailSeat.status)">
                  {{ getStatusText(detailSeat.status) }}
                </view>
              </view>
              <view class="seat-details">
                <view class="detail-item">
                  <text class="detail-label">区域</text>
                  <text class="detail-value">{{ detailSeat.area }}</text>
                </view>
                <view class="detail-item">
                  <text class="detail-label">价格</text>
                  <text class="detail-value price">¥{{ detailSeat.price }}/小时</text>
                </view>
                <view v-if="detailSeat.status === 'occupied'" class="detail-item">
                  <text class="detail-label">剩余时间</text>
                  <text class="detail-value">{{ getRemainingTime(detailSeat) }}</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 设备配置 -->
          <view class="detail-section">
            <text class="detail-title">设备配置</text>
            <view class="equipment-grid">
              <view class="equipment-item">
                <text class="equipment-icon">💻</text>
                <text class="equipment-label">CPU</text>
                <text class="equipment-value">{{ detailSeat.equipment.cpu }}</text>
              </view>
              <view class="equipment-item">
                <text class="equipment-icon">🎮</text>
                <text class="equipment-label">显卡</text>
                <text class="equipment-value">{{ detailSeat.equipment.gpu }}</text>
              </view>
              <view class="equipment-item">
                <text class="equipment-icon">🧠</text>
                <text class="equipment-label">内存</text>
                <text class="equipment-value">{{ detailSeat.equipment.memory }}</text>
              </view>
              <view class="equipment-item">
                <text class="equipment-icon">🖥️</text>
                <text class="equipment-label">显示器</text>
                <text class="equipment-value">{{ detailSeat.equipment.monitor }}</text>
              </view>
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="popup-actions">
            <button 
              v-if="detailSeat.status === 'available'" 
              class="btn btn-primary btn-block"
              @click="selectSeatAndBook"
            >
              选择并预约
            </button>
            <button 
              v-else 
              class="btn btn-secondary btn-block" 
              disabled
            >
              {{ getStatusText(detailSeat.status) }}
            </button>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useSeatStore } from '@/stores/seat'
import { useUserStore } from '@/stores/user'
import { formatTime, showError, showSuccess } from '@/utils/common'

const seatStore = useSeatStore()
const userStore = useUserStore()

// 响应式数据
const selectedArea = ref('all')
const detailSeat = ref(null)
const seatDetailPopup = ref(null)
const refreshing = ref(false)
const showDetailPopup = ref(false)

// 计算属性
const visibleAreas = computed(() => {
  if (selectedArea.value === 'all') {
    return seatStore.seatLayout.areas
  }
  return seatStore.seatLayout.areas.filter(area => area.name === selectedArea.value)
})

const visibleSeats = computed(() => {
  if (selectedArea.value === 'all') {
    return seatStore.seats
  }
  return seatStore.getSeatsByArea(selectedArea.value)
})

const selectedSeatInfo = computed(() => {
  return seatStore.selectedSeatInfo
})

// 方法
const onRefresh = async () => {
  refreshing.value = true
  try {
    await seatStore.refreshSeats()
    showSuccess('刷新成功')
  } catch (error) {
    showError('刷新失败')
  } finally {
    refreshing.value = false
  }
}

const filterByArea = (area) => {
  selectedArea.value = area
}

const getAreaSeats = (area) => {
  return seatStore.seats.filter(seat => {
    const row = Math.floor((seat.position - 1) / seatStore.seatLayout.cols)
    return row >= area.startRow && row <= area.endRow
  })
}

const getAreaAvailableCount = (area) => {
  const areaSeats = getAreaSeats(area)
  return areaSeats.filter(seat => seat.status === 'available').length
}

const getAreaTotalCount = (area) => {
  return getAreaSeats(area).length
}

const getSeatClass = (seat) => {
  const classes = ['seat']
  classes.push(seat.status)
  
  if (seat.area === 'VIP区') {
    classes.push('vip')
  }
  
  if (seatStore.selectedSeats.includes(seat.id)) {
    classes.push('selected')
  }
  
  return classes.join(' ')
}

const getStatusClass = (status) => {
  const statusMap = {
    available: 'status-available',
    occupied: 'status-occupied',
    maintenance: 'status-maintenance'
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    available: '空闲',
    occupied: '占用中',
    maintenance: '维修中'
  }
  return statusMap[status] || '未知'
}

const selectSeat = (seat) => {
  if (seat.status !== 'available') {
    showSeatDetail(seat)
    return
  }
  
  const success = seatStore.selectSeat(seat.id)
  if (success) {
    showSuccess(`已选择座位 ${seat.number}`)
    
    // 震动反馈
    uni.vibrateShort()
  }
}

const showSeatDetail = (seat) => {
  detailSeat.value = seat
  showDetailPopup.value = true
  if (seatDetailPopup.value) {
    seatDetailPopup.value.open()
  }
}

const closeSeatDetail = () => {
  console.log('关闭座位详情弹窗')
  showDetailPopup.value = false
  if (seatDetailPopup.value) {
    seatDetailPopup.value.close()
  }
  // 延迟清空数据，避免关闭动画时内容闪烁
  setTimeout(() => {
    detailSeat.value = null
  }, 300)
}

const selectSeatAndBook = () => {
  if (detailSeat.value) {
    seatStore.selectSeat(detailSeat.value.id)
    closeSeatDetail()
    goToBooking()
  }
}

const getRemainingTime = (seat) => {
  if (seat.status !== 'occupied' || !seat.occupiedUntil) return ''
  
  const now = new Date()
  const endTime = new Date(seat.occupiedUntil)
  const remaining = endTime.getTime() - now.getTime()
  
  if (remaining <= 0) return '即将结束'
  
  const hours = Math.floor(remaining / (1000 * 60 * 60))
  const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60))
  
  if (hours > 0) {
    return `${hours}h${minutes}m`
  }
  return `${minutes}m`
}


// 预约座位的鉴权操作
const goToBooking = () => {
  if (!userStore.isLoggedIn) {
    uni.showModal({
      title: '请先登录',
      content: '预约座位需要先登录账户',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }
      }
    })
    return
  }
  
  if (seatStore.selectedSeats.length === 0) {
    showError('请先选择座位')
    return
  }
  
  uni.navigateTo({
    url: '/pages/booking/booking'
  })
}

// 生命周期
onMounted(() => {
  // 初始化座位数据
  if (seatStore.seats.length === 0) {
    seatStore.initMockSeats()
  }
})
</script>

<style lang="scss" scoped>
.seat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-background);
}

// 顶部工具栏
.toolbar {
  background: white;
  padding: 16px;
  border-bottom: 1px solid var(--color-border);
  box-shadow: var(--shadow-sm);
}

.seat-legend {
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 3px;

  &.available {
    background: var(--color-success);
  }

  &.occupied {
    background: var(--color-error);
  }

  &.selected {
    background: var(--color-primary);
  }

  &.maintenance {
    background: var(--color-warning);
  }

  &.vip {
    background: linear-gradient(135deg, var(--color-vip), var(--color-gaming));
  }
}

.legend-text {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.area-filter {
  margin-bottom: 12px;
}

.filter-scroll {
  white-space: nowrap;
}

.filter-item {
  display: inline-block;
  padding: 8px 16px;
  margin-right: 8px;
  background: var(--color-background);
  border-radius: var(--radius-xl);
  font-size: 14px;
  color: var(--color-text-secondary);
  transition: all var(--transition-normal);

  &.active {
    background: var(--color-primary);
    color: white;
    box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
  }

  &:active {
    transform: scale(0.95);
  }
}

.seat-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-text {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-primary);
}

.update-time {
  font-size: 12px;
  color: var(--color-text-secondary);
}

// 座位容器
.seat-container {
  flex: 1;
  padding: 12px;
  background: var(--color-background);
  overflow-x: hidden;
  overflow-y: auto;
}

.seat-layout {
  width: 100%;
}

.area-section {
  margin-bottom: 24px;
  background: white;
  border-radius: var(--radius-lg);
  padding: 16px;
  box-shadow: var(--shadow-sm);
}

.area-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 8px;
}

.area-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.area-count {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.seat-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 6px;
  width: 100%;
  padding: 0 4px;
}

.seat-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: var(--radius-md);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: 600;
  min-height: 50px;
  transition: transform var(--transition-fast), box-shadow var(--transition-fast);
  cursor: pointer;
  will-change: transform;

  &.available {
    background: var(--color-success);
    color: white;

    &:active {
      transform: scale(0.9);
    }
  }

  &.occupied {
    background: var(--color-error);
    color: white;
  }

  &.maintenance {
    background: var(--color-warning);
    color: white;
  }

  &.vip {
    background: linear-gradient(135deg, var(--color-vip), var(--color-gaming));
    color: white;

    &.available:active {
      transform: scale(0.9);
    }
  }

  &.selected {
    background: var(--color-primary) !important;
    color: white;
    box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.4);
    transform: scale(1.05);
    z-index: 10;
  }
}

.seat-number {
  font-size: 11px;
  font-weight: bold;
  margin-bottom: 2px;
}

.seat-time {
  font-size: 8px;
  opacity: 0.9;
}

.maintenance-icon {
  position: absolute;
  top: 2px;
  right: 2px;

  .icon {
    font-size: 8px;
  }
}

.vip-badge {
  position: absolute;
  top: -2px;
  right: -2px;
  background: var(--color-gaming);
  border-radius: var(--radius-xs);
  padding: 1px 3px;

  .vip-text {
    font-size: 6px;
    color: white;
    font-weight: bold;
  }
}



// 底部操作栏
.bottom-actions {
  background: white;
  padding: 16px;
  border-top: 1px solid var(--color-border);
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
}

.selected-info {
  flex: 1;
}

.selected-seat {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 4px;
}

.seat-name {
  font-size: 20px;
  font-weight: bold;
  color: var(--color-text-primary);
}

.seat-area {
  font-size: 12px;
  color: var(--color-text-secondary);
  padding: 2px 6px;
  background: var(--color-background);
  border-radius: var(--radius-sm);
}

.seat-price {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-text {
  font-size: 16px;
  color: var(--color-primary);
  font-weight: 600;
}

.price-desc {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.booking-btn {
  background: linear-gradient(135deg, var(--color-primary), var(--color-primary-light));
  color: white;
  border: none;
  border-radius: var(--radius-lg);
  padding: 14px 24px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
  transition: all var(--transition-normal);

  &:active {
    transform: scale(0.95);
  }

  .btn-text {
    color: white;
  }

  .btn-icon {
    font-size: 18px;
  }
}

// 座位详情弹窗
.seat-detail-popup {
  background: white;
  border-radius: var(--radius-xl) var(--radius-xl) 0 0;
  max-height: 85vh;
  min-height: 60vh;
  overflow: hidden;
  position: relative;
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.15);
}

// 拖拽指示器
.drag-indicator {
  display: flex;
  justify-content: center;
  padding: 12px 0 8px;
  background: white;
  border-radius: var(--radius-xl) var(--radius-xl) 0 0;
}

.drag-bar {
  width: 36px;
  height: 4px;
  background: var(--color-text-tertiary);
  border-radius: 2px;
  opacity: 0.6;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 20px 16px;
  border-bottom: 1px solid var(--color-border);
  background: white;
  position: sticky;
  top: 0;
  z-index: 10;
}

.popup-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.popup-close {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  background: var(--color-background);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-normal);
  cursor: pointer;
  position: relative;
  z-index: 1000;

  &:active {
    transform: scale(0.9);
    background: var(--color-border);
  }

  &:hover {
    background: var(--color-border);
  }

  // 增加点击区域
  &::before {
    content: '';
    position: absolute;
    top: -5px;
    left: -5px;
    right: -5px;
    bottom: -5px;
    border-radius: 25px;
  }
}

.close-icon {
  font-size: 22px;
  color: var(--color-text-secondary);
  font-weight: bold;
  line-height: 1;
}

.seat-detail-content {
  height: calc(85vh - 120px);
  padding: 0 20px 20px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  background: white;
}

.detail-section {
  margin-bottom: 32px;

  &:first-child {
    margin-top: 16px;
  }

  &:last-child {
    margin-bottom: 40px;
  }
}

.detail-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
  margin-bottom: 12px;
  display: block;
}

.seat-info-card {
  background: var(--color-background);
  border-radius: var(--radius-lg);
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid var(--color-border);
}

.seat-main-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.seat-big-number {
  font-size: 32px;
  font-weight: bold;
  color: var(--color-text-primary);
}

.seat-status-badge {
  padding: 6px 12px;
  border-radius: var(--radius-md);
  font-size: 12px;
  font-weight: 500;

  &.status-available {
    background: rgba(52, 199, 89, 0.1);
    color: var(--color-success);
  }

  &.status-occupied {
    background: rgba(255, 59, 48, 0.1);
    color: var(--color-error);
  }

  &.status-maintenance {
    background: rgba(255, 149, 0, 0.1);
    color: var(--color-warning);
  }
}

.seat-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-label {
  font-size: 14px;
  color: var(--color-text-secondary);
}

.detail-value {
  font-size: 14px;
  color: var(--color-text-primary);
  font-weight: 500;

  &.price {
    color: var(--color-primary);
    font-weight: 600;
  }
}

.equipment-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-top: 16px;
}

.equipment-item {
  background: var(--color-background);
  border-radius: var(--radius-lg);
  padding: 20px 16px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  border: 1px solid var(--color-border);
  transition: all var(--transition-normal);

  &:active {
    transform: scale(0.98);
    background: rgba(0, 122, 255, 0.05);
  }
}

.equipment-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.equipment-label {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.equipment-value {
  font-size: 14px;
  color: var(--color-text-primary);
  font-weight: 500;
}

.popup-actions {
  padding: 24px 20px 32px;
  border-top: 1px solid var(--color-border);
  background: white;
  position: sticky;
  bottom: 0;
  margin-top: auto;
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  color: var(--color-text-tertiary);
  margin-bottom: 16px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
}

// 按钮样式
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 24px;
  border: none;
  border-radius: var(--radius-lg);
  font-size: 16px;
  font-weight: 500;
  text-align: center;
  cursor: pointer;
  transition: all var(--transition-normal);

  &:active:not(:disabled) {
    transform: scale(0.95);
  }

  &.btn-primary {
    background: var(--color-primary);
    color: white;
    box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
  }

  &.btn-secondary {
    background: var(--color-background);
    color: var(--color-text-secondary);
    border: 1px solid var(--color-border);
  }

  &.btn-block {
    width: 100%;
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

// 响应式适配
@media (max-width: 375px) {
  .seat-grid {
    grid-template-columns: repeat(5, 1fr);
    gap: 4px;
  }

  .seat-item {
    min-height: 44px;
    font-size: 10px;
  }

  .seat-number {
    font-size: 9px;
  }

  .seat-time {
    font-size: 7px;
  }
}
</style>
